package com.design.util.moveBox;

import com.design.method.error.ParserError;

import java.io.*;

public class MapParser {
    public static MapMethod parser(File file) throws ParserError {
        BufferedReader reader = null;
        int playerX;
        int playerY;
        Box[][] map;
        try{
            reader = new BufferedReader(new FileReader(file));
            int size = Integer.parseInt(reader.readLine());
            playerX = Integer.parseInt(reader.readLine());
            playerY = Integer.parseInt(reader.readLine());
            map = new Box[size][size];
            for(int y = 0; y < size; y ++){
                char[] chars = reader.readLine().toCharArray();
                for(int x = 0; x < size; x  ++){
                    Picture picture = Picture.get(chars[x]);
                    if(picture == null){
                        throw new ParserError("读取行出错 非法的字符 " + chars[x]);
                    }
                    map[y][x] = new Box(picture,x,y);
                }
            }
        }catch(FileNotFoundException e){
            throw new ParserError("找不到文件");
        }catch(Exception e){
            throw new ParserError("读取行出错");
        }finally{
            try{
                if(reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new MapMethod(map,file,playerX,playerY);
    }
    public static void preserve(MapMethod method){
        BufferedWriter writer = null;
        try{
            writer = new BufferedWriter(new FileWriter(method.getFile()));
            Box[][] map = method.getMap();
            writer.write(map.length + "");
            writer.newLine();
            writer.write(method.getPlayerX() + "");
            writer.newLine();
            writer.write(method.getPlayerY() + "");
            for (Box[] boxes : map) {
                StringBuilder str = new StringBuilder();
                for (int x = 0; x < map.length; x++) {
                    str.append(boxes[x].getName());
                }
                writer.newLine();
                writer.write(str.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(writer != null){
                try{
                    writer.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
